package main

import (
	"fmt"
	lib "im/libs"
	"im/model"
	protos "im/pb"
)


var c *model.Chat
var token *model.Token


var users map[string]string = map[string]string{
	"admin": "123",
	"abc":   "123",
	"def":   "123",
}

var uids map[string]uint64 = map[string]uint64{
	"admin": 123,
	"abc":   125,
	"def":   210,
}

func chatHandle(t *(lib.Task)) {

	//t.Client.Write([]byte("Hello"))
	///fmt.Println("from", t.Client.RemoteAddr())
	defer t.Client.Close()

		for{
			req, err := lib.ReadReq(t.Client)
			fmt.Printf("get %+v, err:%+v\n", req,err)
			if err != nil {
				break
			}
			switch req.Command {
			case protos.Command_SEND_MSG:
				token,err:=token.Get(req.Token)
				if err != nil{
					r := &protos.Response{Command: protos.Command_SEND_MSG,Errcode: protos.ErrCode_SERVER_ERR}
					r.Errmsg = err.Error()
					rsp, _ := lib.EncodeRsp(r)
					t.Client.Write(rsp)
					break
				}
				if req.Uid ==0 {
					req.Uid =uids[req.Username]
				}
				err = c.SendToUser(token.Uid,req.Uid,req.Msg)
				if err != nil{
					r := &protos.Response{Command: protos.Command_SEND_MSG,Errcode: protos.ErrCode_SERVER_ERR}
					r.Errmsg = err.Error()
					rsp, _ := lib.EncodeRsp(r)
					t.Client.Write(rsp)
					break
				}
				r := &protos.Response{Command: protos.Command_SEND_MSG}
				rsp, _ := lib.EncodeRsp(r)
				t.Client.Write(rsp)
			case protos.Command_PULL_MSG:
				token,err:=token.Get(req.Token)
				if err != nil{
					r := &protos.Response{Command: protos.Command_PULL_MSG,Errcode: protos.ErrCode_SERVER_ERR}
					r.Errmsg = err.Error()
					rsp, _ := lib.EncodeRsp(r)
					t.Client.Write(rsp)
					break
				}
				msg,err := c.RecvUser(token.Uid)
				if err != nil{
					r := &protos.Response{Command: protos.Command_PULL_MSG,Errcode: protos.ErrCode_SERVER_ERR}
					r.Errmsg = err.Error()
					rsp, _ := lib.EncodeRsp(r)
					t.Client.Write(rsp)
					break
				}
				r := &protos.Response{Command: protos.Command_PULL_MSG}
				r.Msg = &protos.Msg{Msg:msg.Text,Uid:msg.Uid}
				rsp, _ := lib.EncodeRsp(r)
				t.Client.Write(rsp)
			default:
				r := &protos.Response{Command: protos.Command_SEND_MSG,Errcode: protos.ErrCode_SERVER_ERR}
				rsp, _ := lib.EncodeRsp(r)
				t.Client.Write(rsp)
			}
		}

	}


func main() {
	redis, err := lib.NewRedisConfig("./config")
	if err != nil {
		panic("redis config load failed.")
	}

	if err != nil {
		panic("token generate failed.")
	}
	if r, e := redis.Servers["user"]; e {
		token,err = model.NewToken(&r)
		if err != nil {
			panic("redis config connect failed.")
		}
	} else {
		panic("redis config load failed.")
	}

	if r, e := redis.Servers["chat"]; e {
		c, err = model.NewChat(&r)
		if err != nil {
			panic("redis config connect failed.")
		}
		s, _ := lib.NewServer("127.0.0.1", 1002, 10, chatHandle)
		s.Start()
	} else {
		panic("redis config load failed.")
	}

}
